import {page, pageFunc} from "../common/PageBuilder";
import {BasePage, BasePageData} from "../common/core/BasePage";
import {DataLoader, field} from "../../modules/coreModule/data/DataLoader";
import {UserPage} from "../common/partPages/UserPage";
import {Message, MessageStatus, SystemSenderId} from "../../modules/messageModule/data/Message"
import {pageMgr} from "../../modules/coreModule/managers/PageManager";
import {MessageDetailPage} from "../messageDetail/MessageDetailPage";
import {QueryPage} from "../common/partPages/QueryPage";
import {blockLoading, showLoading} from "../../modules/coreModule/managers/LoadingManager";
import {CoreLoading} from "../../modules/coreModule/CoreCommon";
import {MessageInterface} from "../../modules/messageModule/MessageCommon";
import {alertMgr} from "../../modules/coreModule/managers/AlertManager";
import {waitForLogin} from "../../modules/userModule/managers/UserManager";


class Data extends BasePageData {

	@field([Message])
	public list: Message[]

}

@page("messageList", "消息列表")
export class messageListPage extends BasePage<Data> {

	public data = new Data();
	public userPage: UserPage = new UserPage();
	public queryPage: QueryPage = new QueryPage(
		this.loadMessages.bind(this), {
			senderId: SystemSenderId,
			status: ["_.neq", MessageStatus.Deleted]
		});

	// @pageFunc
	// onLoad(e) {
	// 	super.onLoad(e);
	// 	this.queryPage.refresh();
	// }
	
	onShow() {
		super.onShow();
		this.queryPage.refresh();
	}

	@showLoading(CoreLoading.Mask)
	@blockLoading
	@waitForLogin
	private async loadMessages(queryParams) {
		const list: Message[] = (await MessageInterface.GetMessages(queryParams))
			.messages.map(m => DataLoader.load(Message, m));
		// 按时间降序排列
		list.sort((ma, mb) => mb.createdAt - ma.createdAt);
		const unreadCnt = list.filter(m => m.status == MessageStatus.Unread).length;
		await this.setData({list, unreadCnt});
	}

	@pageFunc
	toMessageDetail(e) {
		const id = e.currentTarget.dataset.id;
		const message = this.data.list.find(m => m._id == id);
		message.status = MessageStatus.Read;
		pageMgr().push(MessageDetailPage,{id}).then();
		this.setData({list: this.data.list});
	}

	@pageFunc
	async deleteAll() {
		const res = await alertMgr().showAlert("确定删除所有消息？", true);
		if (res.confirm) {
			this.data.list.forEach(m => MessageInterface.DeleteMessage({id: m._id}))
			await this.setData({list: []});
		}
	}
	@pageFunc
	readAll() {
		this.data.list.forEach(m => {
			if (m.isRead) return;
			MessageInterface.ReadMessage({id: m._id});
			m.status = MessageStatus.Read;
		});
		this.setData({list: this.data.list});
	}

}
